package com.ydd.interceptor;

import com.ydd.constant.JwtClaimsConstant;
import com.ydd.context.BaseContext;
import com.ydd.properties.JwtProperties;
import com.ydd.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * jwt令牌校验的拦截器
 */
@Component
@Slf4j
public class JwtTokenUserInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 校验jwt
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }


        // 获取令牌进行判断
        try {
            String token = request.getHeader(jwtProperties.getUserTokenName());// 从请求头获取令牌
            Claims claims = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), token); // 解析令牌
            Integer SysUserId = (Integer) claims.get(JwtClaimsConstant.USER_ID);// 获取id（Integer类型）

            // 将id加入线程局部变量ThreadLocal
            BaseContext.setUserCurrentId(SysUserId);

            return true;  // 放行
        } catch (Exception e) {  //  报错进行反馈
            /* e.printStackTrace();*/
            //否则，发送未认证错误信息
            log.info(request.getRequestURI() + ":请求未通过JWT令牌认证");
//            response.setStatus(401);
            return true;
        }


    }
}
